﻿using Common.Prism.Apps;
using Common.UI.Helper;
using NxChatQQ.Models.Events;
using NxChatQQ.ViewModels.Layouts;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace NxChatQQ.Views.Layouts
{
    /// <summary>
    /// ChatMessageLayout.xaml 的交互逻辑
    /// </summary>
    public partial class ChatMessageLayout : UserControl
    {
        public ChatMessageLayout()
        {
            InitializeComponent();
            this.Loaded += ChatMessageLayout_Loaded;

            Global.EventAggregator.GetEvent<MouseButtonArgsEvent>().Subscribe(GlobalMouseClickEvent);
        }


        private void ChatMessageLayout_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            if (this.DataContext is ChatMessageLayoutViewModel vm)
            {
                vm.ScrollToBottomAction = ScrollToBottom;
            }
        }

        public void ScrollToBottom()
        {
            //Helper.SetScrollToBottom2(xListbox);

            VisualHelper.GetChild<ScrollViewer>(MyScrollViewer)?.ScrollToBottom();

            SetFriendChatViewFocus();
        }

        private void SetFriendChatViewFocus()
        {
            Keyboard.Focus(InputTextBox);
        }

        private void InputTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (this.DataContext is ChatMessageLayoutViewModel vm)
                {
                    if (InputTextBox.Text.Length > 0)
                    {
                        vm.TxtSendCommand?.Execute(InputTextBox.Text.Trim());

                        InputTextBox.Text = "";
                    }
                }
            }
        }


        private void GlobalMouseClickEvent(MouseButtonEventArgs e)
        {
            if (this.DataContext is ChatMessageLayoutViewModel vm)
            {
                if (vm.IsEmojiOpend)
                {
                    // 鼠标点击在 表情 外部  
                    if (!MouseHitElement(e, mGrid))
                    {
                        vm.BtnEmojiCommand?.Execute(null);
                    }
                }

                if (vm.IsFlyoutOpen)
                {
                    // 鼠标点击在 侧边栏 外部  
                    if (!MouseHitElement(e, mEmojiGrid))
                    {
                        vm.BtnRightCommand?.Execute(null);
                    }
                }
            }
        }

        private bool MouseHitElement(MouseButtonEventArgs e, FrameworkElement view)
        {
            var pos = e.GetPosition(view);
            if (pos.X >= 0 && pos.X <= view.ActualWidth &&
                    pos.Y >= 0 && pos.Y <= view.ActualHeight)
            {

                return true;
            }
            return false;
        }
    }
}